package com.yishun.springboot.shiroconfig;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.yishun.springboot.mapper.PermissionMapper;
import com.yishun.springboot.mapper.RoleMapper;
import com.yishun.springboot.mapper.UserMapper;
import com.yishun.springboot.pojo.User;

public class MyRealm extends AuthorizingRealm {
	@Resource
	private UserMapper userDao;
	@Resource
	private RoleMapper roleDao;
	@Resource
	private PermissionMapper permissionDao;

	/**
	 * 获取授权数据(角色权限信息)
	 * 
	 * @param principalCollection
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		// 获取用户的用户名
		String username = (String) principalCollection.iterator().next();
		// 根据用户名查询用户角色
		Set<String> roles = roleDao.getRoleNamesByUsername(username);
		List<Integer> list = userDao.getRoleId(username);
		// 根据用户名查询用户权限
		Set<String> permissions = permissionDao.getPermissionByUsername(list, username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(roles);
		info.setStringPermissions(permissions);

		return info;
	}

	/**
	 * 获取认证的安全数据（从数据库查询到的用户正确数据）
	 * 
	 * @param authenticationToken
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// 参数authenticationToken就是传递的 subject.login(token)
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		// 从token中获取用户名
		String username = token.getUsername();
		// 根据用户名从数据库查询用户安全数据
		User user = userDao.getUserByUsername(username);
		AuthenticationInfo info = new SimpleAuthenticationInfo(username, user.getPassword(), getName());
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.getSession().setAttribute("user", user);
		return info;
	}

}
